import 'dart:isolate';

import 'package:flutter/material.dart';
import 'package:flutter_isolate/flutter_isolate.dart';
import 'package:novel_reader/apk.dart';
import 'package:shared_preferences/shared_preferences.dart';

FlutterIsolate? bgTask;
bool bgRunnng = false;
Future<void> testMyBgTask() async {
  if (bgRunnng) return;
  bgRunnng = true;
  ReceivePort recv = await startMyBgTask();

  SendPort? sender;
  print('fhz: startMyBgTask success');

  recv.listen((message) {
    switch (message[0]) {
      case 0:
        sender = message[1];
      case 1:
        print('fhz: $message');
    }
  });
  Future.doWhile(() async {
    await Future.delayed(const Duration(seconds: 3));
    sender?.send('from foreground task message');
    return true;
  });
  print('fhz: MyBgTask wait message');
  await Future.delayed(const Duration(minutes: 2));
  print('fhz: MyBgTask pause');
  bgTask?.pause();
  await Future.delayed(const Duration(minutes: 1));
  print('fhz: MyBgTask resume');
  bgTask?.resume();
  //bgRunnng = false;
  print('fhz: MyBgTask is stop?');
}

Future<ReceivePort> startMyBgTask() async {
  ReceivePort ret = ReceivePort('novel_reader_1');
  SendPort sender = ret.sendPort;
  bgTask = await FlutterIsolate.spawn(myBgTaskEntry, sender);
  return ret;
}

Future<void> startBgTts(SendPort sender) async {
  bgTask = await FlutterIsolate.spawn(myBgTaskEntry, sender);
}

@pragma('vm:entry-point')
void myBgTaskEntry(SendPort sender) {
  startSpeakTask(sender);
  // ReceivePort recv = ReceivePort('novel_reader_2');
  // SendPort sender2 = recv.sendPort;
  // sender.send([0, sender2]);
  // recv.listen((message) {
  //   print('fhz: in isolate: $message');
  // });
  // Future.doWhile(() async {
  //   await Future.delayed(const Duration(seconds: 5));
  //   sender.send([1, 'from isolate ${DateTime.now()}']);
  //   return true;
  // });
}

List<String> spkList = List<String>.empty();
bool ttsReady = false;
Future<void> startSpeakTask(SendPort? sendPort) async {
  final prefs = await SharedPreferences.getInstance()
    ..reload();
  spkList = prefs.getStringList('spkList')!;
  ttsStart = prefs.getInt('ttsStart')!;
  speed = prefs.getDouble('speed')!;

  //print('fhz: start service : ${spkList.length}');
  if (spkList.isEmpty) {
    print('fhz:list is empty');
    bgTask?.kill();
    return;
  }
  //print('fhz:start speak');
  if (!ttsReady) {
    WidgetsFlutterBinding.ensureInitialized();
    await ttsInit();
    ttsReady = true;
    speakList(spkList, sendPort);
  } else {
    speakList(spkList, sendPort);
  }
}
